package guoanmaker.operator.business.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import guoanmaker.operator.business.model.OperatorCities;
import guoanmaker.operator.business.model.OperatorCity;
import guoanmaker.operator.business.model.OperatorProvince;
import guoanmaker.operator.business.model.PersonalUserLandLog;
import guoanmaker.operator.business.modelnobind.OperatorCitiesMove;
import guoanmaker.operator.business.modelnobind.ProvideCommodityServiceMove;
import guoanmaker.operator.business.modelnobind.ProvideRoomMove;
import guoanmaker.operator.business.modelnobind.Utils;
import guoanmaker.operator.business.repository.OperatorCitiesRepository;
import guoanmaker.operator.business.repository.OperatorCityRepository;
import guoanmaker.operator.business.repository.OperatorProvinceRepository;
import guoanmaker.operator.business.repository.PersonalUserLandLogRepository;
import guoanmaker.operator.helper.common.util.ChineseCharToEn;

/**
 *  
 *
 * @ClassName: OperatorCityService 
 * @Description: OperatorCityService 
 * @author: huZhaoyu 
 * @date 2017/6/28 下午2:56 
 */
@Service
public class OperatorCityService implements OperatorCityServiceInterface {
    private final OperatorCityRepository operatorCityRepository;
    private final OperatorCitiesRepository operatorCitiesRepository;
    
    @PersistenceContext
	private EntityManager manager;
    
    @Autowired
    private  OperatorCitiesRepository OperatorCitiesRepository;
    
    @Autowired
    private  OperatorProvinceRepository operatorProvinceRepository;
    @Autowired
    private PersonalUserLandLogRepository personalUserLandLogRepository;
    @Override
    public Integer countAllById() {
        return operatorCityRepository.countAllByIdIsNotNull();
    }

    @Override
    public Page<OperatorCity> getCityByPageOrderByWeight(Integer page, Integer size) {
        return operatorCityRepository.findAll(new PageRequest(page, size, new Sort(Sort.Direction.DESC, "weight")));
    }

    @Autowired
    public OperatorCityService(OperatorCityRepository operatorCityRepository, OperatorCitiesRepository operatorCitiesRepository) {
        this.operatorCityRepository = operatorCityRepository;
        this.operatorCitiesRepository = operatorCitiesRepository;
    }
    
    public int validateCity(String code){
       String jpql1="select new guoanmaker.operator.business.modelnobind.ProvideRoomMove(r.city.code) from ProvideRoom r ";
 	   Query query1=manager.createQuery(jpql1);
 	   List list1=query1.getResultList();
 	   String jpql2="select new guoanmaker.operator.business.modelnobind.ProvideCommodityServiceMove(r.city.code) from ProvideCommodityServiceRange r ";
 	   Query query2=manager.createQuery(jpql2);
 	   List list2=query2.getResultList();
 	   String usestr=",";
 	   for (int i = 0; i < list1.size(); i++) {
 		   usestr+=((ProvideRoomMove)list1.get(i)).getCityName()+",";
 	   }
 	   for (int i = 0; i < list2.size(); i++) {
 		   usestr+=((ProvideCommodityServiceMove)list2.get(i)).getCode()+",";
 	   }
 	   if(usestr.indexOf(","+code+",")>-1){
 		   return -1;
 	   }
 	   return 1;
    }
    
    @Transactional
    public int saveCity(String code) {
    	code=code==null?"":code;
    	String oldStr=",";
	   List<OperatorCity> OldList=operatorCityRepository.findAll();
	   for (int i = 0; i < OldList.size(); i++) {
		   OperatorCity oc=OldList.get(i);
		   String ss=oc.getCityId();
		   oldStr+=ss+",";
		   if((","+code+",").indexOf(","+ss+",")==-1){
			   String jpql3="delete OperatorCity o where o.cityId=:code";
			   Query query3=manager.createQuery(jpql3).setParameter("code", ss);
	    	   query3.executeUpdate();
		   }
	   }
	   if(!code.equals("")){
		   String[] str=code.split(",");
		   List<OperatorCity>  lists=new ArrayList<OperatorCity>();
		   String ids="";
		   OperatorCity operatorCity=null;
		   for (int i = 0; i < str.length; i++) {
			   if(oldStr.indexOf(","+str[i]+",")>-1){
				   continue;
			   }
			   operatorCity=new OperatorCity();
			   String jpql3="select o from  OperatorCities o where o.code=:code";
			   Query query3=manager.createQuery(jpql3).setParameter("code", str[i]);
	    	   List<OperatorCities> list=query3.getResultList();
	    	   OperatorCities operatorCities=list.get(0);
	    	   String provinceCode=operatorCities.getProvinceCode();
			   ids=str[i];
			   operatorCity.setId(ids);
			   operatorCity.setCityId(ids);
			   operatorCity.setProvinceId(provinceCode);
			   operatorCity.setCreateDate(new Date());
			   lists.add(operatorCity);
		   }
	   operatorCityRepository.save(lists);
	   }
	   return 1;
    }

    @Override
    public List<OperatorCitiesMove> getAllCity() {
    	String jpql="select new guoanmaker.operator.business.modelnobind.OperatorCitiesMove(o.id,o.cityId,o.createDate) "
    			+ "from OperatorCity o";
    	Query query=manager.createQuery(jpql);
    	List<OperatorCitiesMove> list=query.getResultList();
    	for (int i = 0; i < list.size(); i++) {
    		OperatorCitiesMove operatorCitiesMove=list.get(i);
    		OperatorCities operatorCities=operatorCitiesRepository.findByCode(operatorCitiesMove.getCode());
    		String cityname=operatorCities.getName();
    		operatorCitiesMove.setCityName(cityname);
    		ChineseCharToEn ch=new ChineseCharToEn();
    		String initial=ch.getFirstLetter(cityname);
    		operatorCitiesMove.setInitial(initial);
    		list.remove(i);
    		list.add(i,operatorCitiesMove);
		}
         return list;
    }

    @Override
    public Page<OperatorCity> getAllCityByPage(Integer page, Integer size) {
        return operatorCityRepository.findAll(new PageRequest(page, size));
    }

    @Override
    @Transactional
    public void deleteCityById(String id) {
        operatorCityRepository.delete(id);
    }

    @Override
    public OperatorCity getCityById(String id) {
        return operatorCityRepository.findOne(id);
    }

    @Override
    public List<OperatorCity> getCityByStatus(Integer status) {
        return operatorCityRepository.findByStatus(status);
    }

    @Override
    public OperatorCity getByCityId(String cityId) {
        return operatorCityRepository.findByCityId(cityId);
    }

    @Override
    public HashMap<String, Object> getCity2App(String cityName,String username,String landType) {
    	
        HashMap<String, Object> reMap = new HashMap<String, Object>();
        if(null!=username&&!username.equals("")){
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String now=sdf.format(new Date());
		String timeBegin=now+" 00:00:00";
		String timeEnd=now+" 23:59:59";
		String jpql="select l from PersonalUserLandLog l where l.username='"+username+"' and l.landType='"+landType+"' and landTime>='"+timeBegin+"' and landTime<='"+timeEnd+"'";
		Query query = manager.createQuery(jpql);
		List<PersonalUserLandLog> list=query.getResultList();
		PersonalUserLandLog userLandLog=null;
		Date date=new Date();
		if(list!=null&&list.size()>0){
			userLandLog=list.get(0);
			userLandLog.setLandTime(date);
			userLandLog.setLandCount(userLandLog.getLandCount()+1);
			personalUserLandLogRepository.save(userLandLog);
		}else{
			PersonalUserLandLog pUserLandLog=new PersonalUserLandLog();
			pUserLandLog.setLandTime(date);
			pUserLandLog.setLandType(landType);
			pUserLandLog.setUsername(username);
			pUserLandLog.setLandCount(1);
			personalUserLandLogRepository.save(pUserLandLog);
		}
		
        }
        OperatorCities cities = operatorCitiesRepository.findByNameContaining(cityName);
        if (cities == null) {
            reMap.put("inCity", null);
//            reMap.put("error", "查询错误");
        } else
            reMap.put("inCity", cities);
        List<OperatorCity> cityList = operatorCityRepository.findAll();
        for (OperatorCity city : cityList) {
            OperatorCities c = operatorCitiesRepository.findByCode(city.getCityId());
            city.setCityName(c.getName());
        }
        reMap.put("openCity", cityList);
        return reMap;
    }
    public List<Utils> selectAllArea(){
    	List<OperatorCity> operatorCitylist=operatorCityRepository.findAll();
    	String str=",";
    	for (int i = 0; i < operatorCitylist.size(); i++) {
    		OperatorCity operatorCity=operatorCitylist.get(i);
			str+=operatorCity.getCityId()+",";
		}
    	ChineseCharToEn ch=new ChineseCharToEn();
    	String jpql="select new guoanmaker.operator.business.modelnobind.OperatorCitiesMove(o.code,o.name,o.provinceCode) from OperatorCities o";
    	Query query=manager.createQuery(jpql);
    	List<OperatorCitiesMove> list=query.getResultList();
    	List<Utils> lists=new ArrayList<Utils>();
    	Utils utils=null;
    	List<OperatorCities> listnnn=null;
    	for (int i = 0; i < 27; i++) {
    		Character ss=(char) (i+65);
			String initial=ss.toString();
			utils=new Utils(initial,new ArrayList<OperatorCitiesMove>());
    		lists.add(utils);
		}
    	OperatorCitiesMove operatorCities=null;
    	for (int i = 0; i < list.size(); i++) {
    		operatorCities=list.get(i);
    		String code=operatorCities.getCode();
    		if(str.indexOf(","+code+",")!=-1){
    			operatorCities.setIysActive(true);
    		}
    		String cityname=operatorCities.getCityName();
    		String initial=ch.getFirstLetter(cityname);
    		operatorCities.setInitial(initial);
    		char h=initial.charAt(0);
    		Utils util=null;
    		try {
    			util=lists.get(h-65);
    			List<OperatorCitiesMove> listcity=util.getList();
        		listcity.add(operatorCities);
			} catch (Exception e) {
				util=lists.get(26);
				List<OperatorCitiesMove> listcity=util.getList();
	    		listcity.add(operatorCities);
			}
		}
    	Utils utiles=lists.get(26);
    	utiles.setTitle("其它");
    	lists.remove(26);
    	lists.add(26,utiles);
    	return lists;
    }

	@Override
	public List<OperatorCitiesMove> selectAreaByCode(String code) {
		String jpql="select new guoanmaker.operator.business.modelnobind.OperatorCitiesMove(o.code,o.name) "
    			+ "from OperatorCities o where o.provinceCode=:provinceCode";
    	Query query=manager.createQuery(jpql).setParameter("provinceCode", code);
    	List<OperatorCitiesMove> list=query.getResultList();
    	for (int i = 0; i < list.size(); i++) {
    		OperatorCitiesMove citiesMove=list.get(i);
    		String cityname=citiesMove.getCityName();
	    	ChineseCharToEn ch=new ChineseCharToEn();
			String initial=ch.getFirstLetter(cityname);
			citiesMove.setInitial(initial);
			list.remove(i);
	    	list.add(i,citiesMove);
		}
		return list;
	}

	@Override
	public List<OperatorProvince> selectAllPriovince() {
		return operatorProvinceRepository.findAll();
	}
	
	public List<OperatorCity> selectCityforPc(){
		 List<OperatorCity> cityList = operatorCityRepository.findAll();
	        for (OperatorCity city : cityList) {
	            OperatorCities c = operatorCitiesRepository.findByCode(city.getCityId());
	            city.setCityName(c.getName());
	        }
	        return cityList;
	}
    
}
